<template>
  <component
    :is="realComponent"
    v-if="this.realComponent"
    :type="fakeType ? fakeType : null"
    v-bind="$attrs"
  />
</template>

<script>
import allIcons from './AntdIcons.js'
import ExtendIcon from './ExtendIcon.js'
export default {
  name: 'SIcon',
  props: {
    type: { String }
  },
  data() {
    return { realComponent: undefined, fakeType: undefined }
  },
  watch: {
    type() {
      this.init()
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      if (this.type) {
        if (this.type.indexOf('-') > -1) {
          const prefix = this.type.substr(0, this.type.indexOf('-'))
          if (ExtendIcon[prefix] != null) {
            this.fakeType = this.type.slice(this.type.indexOf('-') + 1)
            this.realComponent = ExtendIcon[prefix]
            return
          }
        }
        const fakeType = this.formatName()
        if (fakeType) {
          this.realComponent = allIcons[fakeType]
        } else {
          this.realComponent = null
        }
      }
    },
    formatName() {
      if (!this.type) {
        return null
      }
      let type = ''
      if (this.type.indexOf('-') != -1) {
        const names = this.type.split('-')
        names.forEach((name) => {
          const bs = name.charAt(0)
          const cs = bs.toUpperCase()
          const ds = cs + name.slice(1)
          type = type + ds
        })
        return type
      } else {
        const bs = this.type.charAt(0)
        const cs = bs.toUpperCase()
        type = cs + this.type.slice(1)
      }
      return type
    }
  }
}
</script>

<style lang="less" scoped></style>
